#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 叶建伟
   @Email: yejw46507@hundsun.com
   @Time: 2023/7/12 10:30
   @File: logCheck.py
   日志检测
"""

import paramiko

from DataTest.env import Env

def detect_errors(server='hsrcm-rcce-task', num_lines_before=500, num_lines_after=100,env=None):
    env = Env(env)
    log_file = f'/opt/software/{server}/{server}/logs/app.log'
    command = f"grep -A {num_lines_after} -B {num_lines_before} -i 'error ' {log_file}"
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(env.ip, username=env.linux_user, password=env.linux_pwd)
    stdin, stdout, stderr = ssh.exec_command(command)
    output = stdout.read().decode()
    ssh.close()

    error_lines = output.split('\n')
    errors = []
    for line in error_lines:
       # if 'error ' in line.lower():
            errors.append(line)
    if errors:
        print(f"**{log_file}** 错误日志 :")
        for error in errors:
            print(error)
    else:
        print(f"**{log_file}** 无错误日志.")
    return errors

if __name__ == "__main__":
    server = 'hsrcm-rcce-task'
    env = 'oracle'
    detect_errors(server=server,env=env)


